const { computerService } = require("../service/computer");
const { exec } = require("child_process");
const si = require("systeminformation");

class ComputerController {
  async getCpuID() {
    let cpu = await computerService.getCPUId();
    let mac = computerService.getMacAddresses();
    let hd = await computerService.getDiskSerialNumber();
    let gw = await computerService.getGatewayAddress();
    let gwMac = await computerService.getGatewayMacAddress();
    return {
      cpu,
      mac,
      hd,
      gw,
      gwMac,
    };
  }
  async getsi() {
    const si = require("systeminformation");

    // 获取 CPU 信息
    // si.cpu()
    //     .then(data => console.log(data))
    //     .catch(error => console.error(error));

    // // 获取内存信息
    // si.mem()
    //     .then(data => console.log(data))
    //     .catch(error => console.error(error));

    // // 获取磁盘信息
    // si.diskLayout()
    //     .then(data => console.log(data))
    //     .catch(error => console.error(error));

    // 获取网络信息
    let networkInterfaces = await si.networkInterfaces();
    let mac = computerService.getMacAddresses();
    let gw = await computerService.getGatewayAddress();
    console.log("网络接口信息:");
    // networkInterfaces.forEach((item) => {
    //     console.log(`\n接口名称: ${item.iface}`);
    //     console.log(`  MAC 地址: ${item.mac}`);
    //     console.log(`  IP 地址: ${item.ip4 || '未分配'}`);
    //     console.log(`  子网掩码: ${item.subnet4 || '未分配'}`);
    //     console.log(`  默认网关: ${item.gateway4 || '未设置'}`);
    //     console.log(`  状态: ${item.up ? '在线' : '离线'}`);
    // });
    //let stats = await si.networkStats()
    //    .then(data => console.log(data))
    //    .catch(error => console.error(error));
    return { networkInterfaces, mac, gw };
  }

  async getNewWork() {
    try {
      // 获取所有网络接口信息
      const interfaces = await si.networkInterfaces();

      // 根据不同平台执行相应命令获取路由表
      const routeTable = await new Promise((resolve, reject) => {
        const cmd =
          process.platform === "win32"
            ? "route print"
            : process.platform === "darwin"
            ? "netstat -rn"
            : "ip route show";

        exec(cmd, (error, stdout) => {
          if (error) reject(error);
          else resolve(stdout);
        });
      });

      // 解析路由表获取默认网关
      let defaultGateway = null;

      if (process.platform === "win32") {
        // Windows 路由表解析
        const lines = routeTable.split("\n");
        let inIPv4Section = false;

        for (const line of lines) {
          if (line.includes("IPv4 Route Table")) {
            inIPv4Section = true;
            continue;
          }

          if (line.includes("IPv6 Route Table")) {
            inIPv4Section = false;
            continue;
          }

          if (inIPv4Section && line.trim().startsWith("0.0.0.0")) {
            const parts = line.trim().split(/\s+/);
            if (parts.length >= 3) {
              defaultGateway = parts[2];
              break;
            }
          }
        }
      } else if (process.platform === "darwin") {
        // macOS 路由表解析
        const regex = /default\s+([^\s]+)\s+([^\s]+)/;
        const match = routeTable.match(regex);
        if (match) defaultGateway = match[1];
      } else {
        // Linux 路由表解析
        const regex = /default\s+via\s+([^\s]+)\s+dev\s+([^\s]+)/;
        const match = routeTable.match(regex);
        if (match) defaultGateway = match[1];
      }

      // 构建MAC地址到网关的映射
      const macToGateway = new Map();

      interfaces.forEach((iface) => {
        // 优先使用网卡自身的gateway4字段
        let gateway = iface.gateway4;

        // 如果网卡没有指定网关，使用系统默认网关
        if (!gateway && defaultGateway) {
          gateway = defaultGateway;
        }

        if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
          macToGateway.set(iface.mac, gateway || "未知");
        }
      });

      return Object.fromEntries(macToGateway);
    } catch (error) {
      console.error("获取网关信息时出错:", error);
      return {};
    }
  }

  async getNetworkDetails() {
    return await computerService.getNetworkDetails();
  }
  async getNetWorkToString() {
    return await computerService.getNetWorkToString();
  }
}

ComputerController.toString = () => "[class ExampleController]";

module.exports = ComputerController;
